<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
      @tree-load="treeLoad"
    >
      <template slot="Index" slot-scope="{ row }">
        {{ row.dataIndex }}
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.partcategory_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, add, update, remove, getLazyList, getDetail, getMenuTree, lazyLoadChild, parentList } from '@/api/admin/partcategory';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { mapGetters } from 'vuex';

export default {
  name: 'AdminPartcategory',
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      form: {},
      query: {},
      parentId: 0,
      tableOption: {},
      loading: true,
      attributeData: [],
      controlTypes: [],
      attributeTestModel: {},
      attributeModel: {
        controlType: {
          type: '',
          options: []
        }
      },
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 370px)',
        calcHeight: 30,
        rowKey: 'id',
        rowParentKey: 'parentId',
        menuWidth: 300,
        tip: false,
        tree: true,
        addBtn: true,
        deleteBtn: true,
        editBtn: true,
        lazy: true, // 懒加载
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 155,
        border: true,
        selection: true,
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '序号',
            prop: 'dataIndex',
            fixed: true,
            display: false
          },
          {
            label: '编码',
            prop: 'code',
            search: true,
            order: 3,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              },
              {
                max: 15,
                message: '编码最多输入15个字符'
              }
            ],
            display: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            order: 4,
            display: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              },
              {
                max: 15,
                message: '名称最多输入15个字符'
              }
            ]
          },
          {
            label: '层级',
            prop: 'level',
            type: 'select',
            order: 1,
            dicData: [
              {
                label: '大类',
                value: 1
              },
              {
                label: '小类',
                value: 2
              }
            ],
            change: ({ value }) => {
              if (value === 1) {
                this.form.parentId = '';
              }
            }
          },
          {
            label: '大类',
            prop: 'parentId',
            type: 'select',
            order: 2,
            filterable: true,
            dicData: [],
            // dicUrl: '/api/mes-admin/part-category/list',
            // dicFormatter: (data) => {
            //   return data.data;
            // },
            hide: true,
            props: {
              label: 'name',
              value: 'id'
            },
            rules: [
              {
                required: true,
                message: '请选择大类',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {
              if (form.level === 2) {
                return {
                  parentId: { display: true }
                };
              } else {
                return {
                  parentId: { display: false }
                };
              }
            }
          },
          {
            label: '状态',
            prop: 'status',
            type: 'switch',
            order: 5,
            search: true,
            value: 1,
            dicData: [
              {
                label: '禁用',
                value: 2
              },
              {
                label: '启用',
                value: 1
              }
            ]
          },
          {
            label: '更新用户',
            prop: 'updateUserName',
            display: false
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            display: false
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.partcategory_add, false),
        viewBtn: this.vaildData(this.permission.partcategory_view, false),
        delBtn: this.vaildData(this.permission.partcategory_delete, false),
        editBtn: this.vaildData(this.permission.partcategory_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    expandChange(row, expanded) {
      this.handleTreeDataIndex(row, expanded);
    },
    handleTreeDataIndex(row, checkStatus) {
      if (row.children && row.children.length > 0) {
        row.children.map((d, i) => {
          if (checkStatus) {
            d.dataIndex = row.dataIndex + '-' + (i + 1);
          }
        });
      }
    },
    async beforeOpen(done, type) {
      const res = await parentList();
      const column = this.findObject(this.option.column, 'parentId');
      column.dicData = res.data.data || [];
      done();
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        (res) => {
          // 获取新增数据的相关字段
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '编辑成功!'
          });
          done(row);
        },
        (error) => {
          loading();
        }
      );
    },
    rowSave(row, done, loading) {
      add(row).then(
        (res) => {
          // done(row);
          // 获取新增数据的相关字段
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          done();
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        },
        (error) => {
          loading();
        }
      );
    },
    rowDel(row, index, done) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.data = [];
          this.parentId = 0;
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.data = [];
          this.parentId = 0;
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.parentId = 0;
      this.onLoad(this.page);
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getLazyList(this.parentId, page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data =
          res.data.data &&
          res.data.data.records &&
          res.data.data.records.map((item, index) => {
            item.dataIndex = index + 1;
            return item;
          });
        this.page.total = res.data.data.total;
        this.data = data;
        this.loading = false;
        this.selectionClear();
        this.treeParams = new Map();
      });
    },
    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      lazyLoadChild(parentId).then((res) => {
        let data = res.data.data;
        resolve(data);
      });
    },
    submit() {}
  }
};
</script>

<style lang="scss" scoped>
.overpaymentRatio-value {
  ::v-deep .el-input__inner {
    border: none;
    border-radius: inherit;
    border-bottom: 1px solid #dcdfe6 !important;
  }
}

::v-deep .el-table {
  margin-bottom: 10px;
}

::v-deep .el-table .criterion-select-row {
  background-color: #caf982 !important;
}
</style>
